<?php
/**
 * 测试异步心跳处理
 * 
 * 这个脚本用于验证心跳异步处理是否正常工作
 */

require_once __DIR__ . '/../../vendor/autoload.php';

error_reporting(E_ALL);
ini_set('display_errors', 'on');

// 读取 .env
function loadDotEnv(string $path): array {
    if (!is_file($path)) return [];
    $vars = [];
    foreach (file($path) as $line) {
        $line = trim($line);
        if ($line === '' || $line[0] === '#') continue;
        $pos = strpos($line, '=');
        if ($pos === false) continue;
        $key = trim(substr($line, 0, $pos));
        $val = trim(substr($line, $pos + 1));
        if ((strlen($val) >= 2) && (($val[0] === '"' && substr($val, -1) === '"') || ($val[0] === "'" && substr($val, -1) === "'"))) {
            $val = substr($val, 1, -1);
        }
        $vars[$key] = $val;
    }
    return $vars;
}

$env = loadDotEnv(__DIR__ . '/../../.env');

// Redis配置
$redisConfig = [
    'host' => $env['REDIS_HOST'] ?? getenv('REDIS_HOST') ?: '127.0.0.1',
    'port' => $env['REDIS_PORT'] ?? getenv('REDIS_PORT') ?: 6379,
    'password' => $env['REDIS_PASSWORD'] ?? getenv('REDIS_PASSWORD') ?: '',
    'database' => $env['REDIS_DATABASE'] ?? getenv('REDIS_DATABASE') ?: 0
];

echo "========================================\n";
echo "异步心跳处理测试\n";
echo "========================================\n\n";

// 测试1：Redis连接
echo "[测试1] Redis连接...\n";
try {
    $redis = new Redis();
    $redis->connect($redisConfig['host'], $redisConfig['port'], 2);
    if (!empty($redisConfig['password'])) {
        $redis->auth($redisConfig['password']);
    }
    $redis->select($redisConfig['database']);
    echo "✓ Redis连接成功\n";
} catch (\Throwable $e) {
    echo "✗ Redis连接失败: " . $e->getMessage() . "\n";
    exit(1);
}

// 测试2：清空队列
echo "\n[测试2] 清空队列...\n";
$queueKey = "heartbeat:queue";
$cleared = $redis->del($queueKey);
echo "✓ 队列已清空 (删除 {$cleared} 条记录)\n";

// 测试3：添加测试数据到队列
echo "\n[测试3] 添加测试数据到队列...\n";
$testData = [
    ['sn' => 'TEST001', 'ipAddr' => '192.168.1.100', 'appVersion' => '1.0.0'],
    ['sn' => 'TEST002', 'ipAddr' => '192.168.1.101', 'appVersion' => '1.0.1'],
    ['sn' => 'TEST003', 'ipAddr' => '192.168.1.102', 'appVersion' => '1.0.2'],
];

foreach ($testData as $data) {
    $json = json_encode($data, JSON_UNESCAPED_UNICODE);
    $redis->lPush($queueKey, $json);
    echo "✓ 添加: {$data['sn']}\n";
}

// 测试4：检查队列大小
echo "\n[测试4] 检查队列大小...\n";
$queueSize = $redis->lLen($queueKey);
echo "✓ 队列大小: {$queueSize}\n";

if ($queueSize !== count($testData)) {
    echo "✗ 队列大小不匹配！\n";
    exit(1);
}

// 测试5：读取队列数据
echo "\n[测试5] 读取队列数据...\n";
$items = $redis->lRange($queueKey, 0, -1);
foreach ($items as $i => $item) {
    $data = json_decode($item, true);
    echo "✓ 项目 " . ($i + 1) . ": {$data['sn']}\n";
}

// 测试6：处理队列（模拟处理器）
echo "\n[测试6] 处理队列（模拟处理器）...\n";
$processed = 0;
for ($i = 0; $i < 10; $i++) {
    $data = $redis->rPop($queueKey);
    if (!$data) break;
    
    $heartbeatData = json_decode($data, true);
    echo "✓ 处理: {$heartbeatData['sn']}\n";
    $processed++;
}

echo "✓ 已处理 {$processed} 条记录\n";

// 测试7：检查队列是否为空
echo "\n[测试7] 检查队列是否为空...\n";
$queueSize = $redis->lLen($queueKey);
echo "✓ 队列大小: {$queueSize}\n";

if ($queueSize !== 0) {
    echo "✗ 队列应该为空！\n";
    exit(1);
}

// 测试8：性能测试
echo "\n[测试8] 性能测试（添加1000条记录）...\n";
$startTime = microtime(true);

for ($i = 0; $i < 1000; $i++) {
    $data = [
        'sn' => 'PERF' . str_pad($i, 4, '0', STR_PAD_LEFT),
        'ipAddr' => '192.168.' . ($i % 256) . '.' . (($i / 256) % 256),
        'appVersion' => '1.0.0',
        'timestamp' => time()
    ];
    $json = json_encode($data, JSON_UNESCAPED_UNICODE);
    $redis->lPush($queueKey, $json);
}

$endTime = microtime(true);
$duration = $endTime - $startTime;
$rate = 1000 / $duration;

echo "✓ 添加1000条记录耗时: " . number_format($duration, 3) . " 秒\n";
echo "✓ 添加速率: " . number_format($rate, 0) . " 条/秒\n";

// 测试9：处理性能测试
echo "\n[测试9] 处理性能测试（处理1000条记录）...\n";
$startTime = microtime(true);

$processed = 0;
while (true) {
    $data = $redis->rPop($queueKey);
    if (!$data) break;
    $processed++;
}

$endTime = microtime(true);
$duration = $endTime - $startTime;
$rate = $processed / $duration;

echo "✓ 处理 {$processed} 条记录耗时: " . number_format($duration, 3) . " 秒\n";
echo "✓ 处理速率: " . number_format($rate, 0) . " 条/秒\n";

// 测试10：最终检查
echo "\n[测试10] 最终检查...\n";
$queueSize = $redis->lLen($queueKey);
echo "✓ 队列大小: {$queueSize}\n";

if ($queueSize !== 0) {
    echo "✗ 队列应该为空！\n";
    exit(1);
}

echo "\n========================================\n";
echo "✓ 所有测试通过！\n";
echo "========================================\n";
echo "\n异步心跳处理系统工作正常。\n";
echo "现在可以启动TCP服务器和心跳处理器。\n";

